package com.css.dzj.zfjg.modules.statisticsb.service.impl;

import com.css.dzj.zfjg.common.util.excel.ExcelUtil;
import com.css.dzj.zfjg.modules.statisticsb.entity.QStatisticsb;
import com.css.dzj.zfjg.modules.statisticsb.entity.Statisticsb;
import com.css.dzj.zfjg.modules.statisticsb.mapper.StatisticsbMapper;
import com.css.dzj.zfjg.modules.statisticsb.service.StatisticsbService;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashSet;
import java.util.List;

@Service
public class StatisticsbServiceImpl implements StatisticsbService {
    @Autowired
    private StatisticsbMapper statisticsbMapper;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Override
    public void add(Statisticsb statisticsb) {
        if (statisticsb == null) {
            throw new RuntimeException("实体为空！");
        }
        statisticsbMapper.save(statisticsb);
    }

    @Transactional
    @Override
    public void addFromExcel(MultipartFile file) throws Exception {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 从第一行开始读取
        Integer startRows = 1;
        // 获取输入流
        InputStream is = file.getInputStream();
        // Excel导入导出的单元类
        List<String[]> strings = ExcelUtil.readData(fileType, startRows, true, is);
        // Excel行数据重复
        String address = this.lineRepeat(strings);
        if (address != null) {
            throw new RuntimeException("行重复:" + address + "!");
        }
        for (String[] s : strings) {
            // 将字符串数组数据转换为实体,并且向数据库添加实体数据
            Statisticsb statisticsb = castStatisticsb(s);
            // 省级重复时，覆盖原有数据
            String id = queryIdByProvincial(s[0]);
            if (!StringUtils.isEmpty(id)) {
                statisticsb.setId(id);
            }
            statisticsbMapper.save(statisticsb);
        }
    }

    /**
     * Excel行重复数据提醒
     **/
    private String lineRepeat(List<String[]> strings) {
        HashSet<String> set = new HashSet<>();
        for (String[] s : strings) {
            String address = s[0];
            if (set.contains(address)) {
                return address;
            }
            set.add(address);
        }
        return null;
    }


    /**
     * 根据省级（唯一的）字段查询ID
     *
     * @param provincial
     * @return
     */
    private String queryIdByProvincial(String provincial) {
        QStatisticsb q = QStatisticsb.statisticsb;
        return jpaQueryFactory.select(q.id).from(q).where(q.provincial.eq(provincial)).fetchOne();
    }


    /**
     * 转换实体
     *
     * @param s
     * @return
     */
    private Statisticsb castStatisticsb(String[] s) {
        Statisticsb statisticsb = new Statisticsb();
        try {
            /**
             * 设置excel表格对应的必填字段
             */
            statisticsb.setProvincial(s[0]); //省级
            // 国办信用分级标准 A->E 类企业比例
            statisticsb.setNationalStandardAProportion(s[1]);
            statisticsb.setNationalStandardBProportion(s[2]);
            statisticsb.setNationalStandardCProportion(s[3]);
            statisticsb.setNationalStandardDProportion(s[4]);
            statisticsb.setNationalStandardEProportion(s[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new RuntimeException("表中缺少一列或多列！");
        }
        return statisticsb;
    }

}
